import React from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { Layout } from 'antd'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import DeviceList from './pages/DeviceList'
import DeviceDetail from './pages/DeviceDetail'
import UserManagement from './pages/UserManagement'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import Sidebar from './components/Sidebar'
import Header from './components/Header'

const { Content } = Layout

// 路由保护组件
const ProtectedRoute = ({ children }) => {
  const { user } = useAuth()
  return user ? children : <Navigate to="/login" replace />
}

// 管理员路由保护组件
const AdminRoute = ({ children }) => {
  const { user } = useAuth()
  return user?.role === 'super_admin' ? children : <Navigate to="/dashboard" replace />
}

function AppContent() {
  const { user } = useAuth()
  
  // 如果是登录页面，不显示侧边栏和头部
  if (window.location.pathname === '/login') {
    return (
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    )
  }

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sidebar />
      <Layout>
        <Header />
        <Content style={{ padding: '24px', background: '#f0f2f5' }}>
          <Routes>
            {/* 受保护的路由 */}
            <Route path="/dashboard" element={
              <ProtectedRoute>
                <Dashboard />
              </ProtectedRoute>
            } />
            
            <Route path="/devices" element={
              <ProtectedRoute>
                <DeviceList />
              </ProtectedRoute>
            } />
            
            <Route path="/devices/:deviceId" element={
              <ProtectedRoute>
                <DeviceDetail />
              </ProtectedRoute>
            } />
            
            {/* 管理员路由 */}
            <Route path="/admin/users" element={
              <AdminRoute>
                <UserManagement />
              </AdminRoute>
            } />
            
            {/* 默认重定向 */}
            <Route path="/" element={<Navigate to="/dashboard" replace />} />
            
            {/* 404页面 */}
            <Route path="*" element={<div>页面不存在</div>} />
          </Routes>
        </Content>
      </Layout>
    </Layout>
  )
}

function App() {
  return (
    <AuthProvider>
      <AppContent />
    </AuthProvider>
  )
}

export default App